from .request import api_client
from ..utils.storage import save_auth_info, get_auth_info
from ..utils.config import config

# 获取认证配置
auth_config = config.get('auth', {})
LOGIN_ENDPOINT = auth_config.get('login_endpoint', '/auth/login')
LOGOUT_ENDPOINT = auth_config.get('logout_endpoint', '/auth/logout')

def login(username, password):
    """用户登录并保存认证信息"""
    try:
        response = api_client.post(LOGIN_ENDPOINT, json={
            'username': username,
            'password': password
        })
        response.raise_for_status()  # 如果请求失败，抛出异常
        
        data = response.json()
        
        # 提取token
        token = data.get('token', '')
        
        # 提取cookies
        cookies = {}
        for cookie in api_client.session.cookies:
            cookies[cookie.name] = cookie.value
        
        # 保存到auth.json
        save_auth_info({'token': token, 'cookies': cookies})
        
        return data
    except Exception as e:
        print(f"登录失败: {e}")
        raise

def check_login_status():
    """检查登录状态"""
    auth_info = get_auth_info()
    return bool(auth_info.get('token'))

def logout():
    """用户登出"""
    try:
        response = api_client.post(LOGOUT_ENDPOINT)
        response.raise_for_status()
        
        # 清除认证信息
        save_auth_info({'token': '', 'cookies': {}})
        
        # 清除session中的cookies
        api_client.session.cookies.clear()
        
        return True
    except Exception as e:
        print(f"登出失败: {e}")
        raise